$('#form-submit').on('click', function(){  //提交数据
    var form = this.form;
    var _data = $(form).serializeObject();
    if(form.memberId.value=='') {
        layer.msg("请选择村民!");
        return;
    }
    if(form.povertyreason.value==='0') {
        layer.msg('请选择致贫原因');
        return;
    }
    if(form.description.value.trim()=='') {
        layer.msg("请填写贫困描述");
        form.description.focus();
        return;
    }    
    var price = form.perincome.value;
    var price_reg = /^(([0-9]+[\.]?[0-9]+)|[1-9])$/;
    if(!price_reg.test(price)){
        layer.msg('价格格式不正确！');
        form.perincome.focus();
        return;
    }
    var price_reg2 = /^\d+(\.\d{1,2})?$/;
    if(!price_reg2.test(price)){
        layer.msg('价格小数点后只有两位！');
        form.perincome.focus();
        return;
    }
    if(form.familymember.value.trim()=='') {
        layer.msg("请填写家庭人口数");
        form.familymember.focus();
        return;
    }
    if(form.relation.value.trim()=='') {
        layer.msg("请填写与户主关系");
        form.relation.focus();
        return;
    }
    var num_reg = /^\+?[1-9][0-9.]*$/;
    if(!num_reg.test(form.housearea.value)){
        layer.msg('请正确填写住房面积');
        form.housearea.focus();
        return;
    }
    if(!num_reg.test(form.farmlandarea.value)) {
        layer.msg("请正确填写耕地面积");
        form.farmlandarea.focus();
        return;
    }
    if(form.outPovertyYear.value=='') {
        layer.msg("请填写脱贫或计划脱贫年份");
        form.outPovertyYear.focus();
        return;
    }
    if(form.outPovertyYear.value.length < 4) {
        layer.msg("请填写4位数字的年份");
        form.outPovertyYear.focus();
        return;
    }
    if(_data.aidingPlan==undefined) {
        layer.msg("请选择帮扶计划")
        return;
    }
    if(form.aidingId.value=='') {
        layer.msg("请选择帮扶人!");
        return;
    }

    if(typeof(_data.aidingPlan) == 'object') {
        _data.aidingPlan = _data.aidingPlan.join(",");
    }
    if(form.memberId.value == form.aidingId.value) {
        layer.msg("贫困户与帮扶人不能同为一人!");
        return;
    }
    $("#form-submit").attr("disabled","disabled");
    delete(_data.tagId);

    $.ajax({
        url : posturl,
        type : 'post',
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        data : JSON.stringify(_data),
    }).done(function(data) {
        if (data.code == 1) {
            layer.msg('保存成功');
            window.location.href= data.url; //加载页面数据
        } else if (data.code === 0 ) {  // 错误
            $("#form-submit").removeAttr("disabled");
            layer.msg(data.msg);
        }
    });
});


$('.add-btn').on('click', function(){   //
    var villageId = $('.village').find('option:selected').val();
    if(!villageId || villageId == 0) {
        layer.msg('请先选择乡村');
        return;
    }
    var title = $(this).attr('data-title');
    var content = '<div class="col-md-9"><div class="form-inline"><form id="searchForm" class="relative row"><input type="text" class="form-control" name="title" placeholder="姓名" maxlength="44"><button type="button" id="doQuery" class="btn btn-success" title="筛选"> <i class="fa fa-search"></i> 筛选</button></form></div></div>'+
    '<table class="table" id="memberAll"><thead><tr><th> 姓名 </th><th> 性别 </th><th> 出生年月 </th><th> 身份证号 </th><th> 操作 </th></tr></thead></table>';
    var options = {
        'width' : '1000px',
    };
    open_modal(title, content, options);
    var table = $('#memberAll');

    table.dataTable({
        "processing": true, 
        "ordering": false, // 禁止排序
        serverSide: true,
        "ajax": {
            url:memberlist,
            data : {'villageId':villageId},
        },
        "autoWidth": false,
        "columns": [
            {"width": "20%","data": "name"},
            {"width": "20%","data": "gender"},
            {"width": "20%","data": "birthday",},
            {"width": "20%","data": "identityNumber"},
            {"width": "30%","data": "null","defaultContent": "<button type=\"button\" class=\"btn btn_select_role \">选取</button>"}
        ],
        "language":{    
            "lengthMenu": "每页显示 _MENU_ 条记录",
            "emptyTable": "暂无数据记录",
            "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
            "zeroRecords": "没有搜索到匹配记录",
            "infoEmpty": "",
            "infoFiltered": "",
            "processing": "数据加载中,请稍后...",
            "paginate": {
                "first": "首页",
                "previous": "",
                "next": "",
                "last": "末页"
            }
        },
        "pageLength": 7,
        "columnDefs": [{
            "orderable": false,
        }],
        "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
            "<t>" +
            "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
        "fnCreatedRow": function(nRow, aData, iDataIndex){   //标识已选数据，使其不能再次被选
            var tagId = $("input[name='tagId']").val() + ',';
            var curentId = $("input[name='memberId']").val();
            if(tagId.indexOf(aData['id']+',') >= 0) {  //标识已选中村民
                $(nRow).find(".btn_select_role").prop("disabled", true);
            }
            if(curentId == aData['id']) {
                $(nRow).find(".btn_select_role").attr('style','background:#5cb85c');
            }
        },
        "fnInitComplete": function() {}
    });
    //选中
    table.on('click', '.btn_select_role', function(event) {
        var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
        var id=oData_arr[0].id;  //member表ID
        var selecttxt = oData_arr[0].name;  //姓名
        $("#povertymember_form").find('input[name="memberId"]').val(id);
        $("#povertymember_form .add-btn").html(selecttxt);
        $(this).parents(".modal").modal('hide');
    });

    $('#doQuery').click(function(event){  //按名称搜索
        var title =   $("#searchForm input[name='title']").val();
        console.log(title);
        var param={"name":title};
        $('#memberAll').DataTable().search(JSON.stringify(param)).draw();     
    });
});

$('.add-btn-aid').on('click', function(){    //选择帮扶人
    var villageId = $('.village').find('option:selected').val();
    if(!villageId || villageId == 0) {
        layer.msg('请先选择乡村');
        return;
    }
    var title = $(this).attr('data-title');
    var content = '<div class="col-md-9"><div class="form-inline"><form id="searchForm" class="relative row"><input type="text" class="form-control" name="title" placeholder="姓名" maxlength="44"><button type="button" id="doQuery" class="btn btn-success" title="筛选"> <i class="fa fa-search"></i> 筛选</button></form></div></div>'+
    '<table class="table" id="memberAll"><thead><tr><th> 姓名 </th><th> 性别 </th><th> 出生年月 </th><th> 身份证号 </th><th> 操作 </th></tr></thead></table>';
    var options = {
        'width' : '1000px',
    };
    open_modal(title, content, options);
    var table_aid = $('#memberAll');

    table_aid.dataTable({
        "processing": true, 
        "ordering": false, // 禁止排序
        serverSide: true,
        "ajax": {
            url:memberaidlist,
            data : {'villageId':villageId},
        },
        "autoWidth": false,
        "columns": [
            {"width": "20%","data": "name"},
            {"width": "20%","data": "gender"},
            {"width": "20%","data": "birthday",},
            {"width": "20%","data": "identityNumber"},
            {"width": "30%","data": "null","defaultContent": "<button type=\"button\" class=\"btn btn_select_role \">选取</button>"}
        ],
        "language":{    
            "lengthMenu": "每页显示 _MENU_ 条记录",
            "emptyTable": "暂无数据记录",
            "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
            "zeroRecords": "没有搜索到匹配记录",
            "infoEmpty": "",
            "infoFiltered": "",
            "processing": "数据加载中,请稍后...",
            "paginate": {
                "first": "首页",
                "previous": "",
                "next": "",
                "last": "末页"
            }
        },
        "pageLength": 5,
        "columnDefs": [{
            "orderable": false,
        }],
        "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
            "<t>" +
            "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
        "fnCreatedRow": function(nRow, aData, iDataIndex){
            var curentId = $("input[name='aidingId']").val();
            if(curentId == aData['id']) {
                $(nRow).find(".btn_select_role").attr('style','background:#5cb85c');
            }
        },
        "fnInitComplete": function() {}
    });
    //选中
    table_aid.on('click', '.btn_select_role', function(event) {
        var oData_arr = table_aid.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
        var id=oData_arr[0].id;  //member表ID
        var selecttxt = oData_arr[0].name;  //姓名
        $("#povertymember_form").find('input[name="aidingId"]').val(id);
        $("#povertymember_form .add-btn-aid").html(selecttxt);
        $(this).parents(".modal").modal('hide');
    });

    $('#doQuery').click(function(event){  //按名称搜索
        var title =   $("#searchForm input[name='title']").val();
        console.log(title);
        var param={"name":title};
        $('#memberAll').DataTable().search(JSON.stringify(param)).draw();     
    });
});
